package com.tank.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;

import com.tank.core.TankModel;

public class TankDaoSupport extends HibernateDaoSupport {
	
	
	JdbcTemplate mJdbcTemplate;
	
	@Autowired
	@Qualifier("sessionFactory")
	public void setSessionFactoryOverride(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}
	
	public JdbcTemplate getJdbcTemplate() {
		return mJdbcTemplate;
	}
	@Autowired
	@Qualifier("jdbcTemplate")
	public void setJdbcTemplate(JdbcTemplate mJdbcTemplate) {
		this.mJdbcTemplate = mJdbcTemplate;
	}
	
	
	public TankModel queryForModelBySQL(String sql, int pageNo,int pageSize, String orderStr) {
		TankModel tm = TankModel.newInstance();
		String sqlUpper = sql.toUpperCase();
		
		int i = sqlUpper.indexOf("FROM");

		if (i >= 0) {
			sqlUpper = "SELECT COUNT(1) " + sqlUpper.substring(i);
		}

		int total = mJdbcTemplate.queryForInt(sqlUpper);
		if(total>0){
			int pageCount=total/pageSize+(total%pageSize==0?0:1);
			pageNo=pageNo<1?1:(pageNo>pageCount?pageCount:pageNo) ;
			int startId=(pageNo-1)*pageSize;
			
			sql = sql + orderStr + "  limit " + startId + "," + pageSize;
			System.out.println(sql);
			System.out.println(sqlUpper);
			List data = mJdbcTemplate.queryForList(sql);
			tm.setData(data);
			
			tm.setAttribute("pageCount", pageCount);
			tm.setAttribute("pageNo", pageNo);
			tm.setAttribute("pageSize", pageSize);
			tm.setAttribute("total", total);
			
		}else{
			tm.setSuccess(false);
			tm.setMessage("没有数据！");
		}
		return tm;
	}
	
	
	
}
